package com.leetcode.sorts.tree;

import java.util.*;

/**
 * @Author: WuPeng
 * @Date: 2021/6/2 5:16 下午
 *
 * 94.二叉树的中序遍历
 *
 */
public class InOrder_94 {

    public static List<Integer> inOrderTraversal(TreeNode root){
        List<Integer> res = new ArrayList<>();
        inOrder(res, root);
        return res;
    }

    private static void inOrder(List<Integer> res, TreeNode node) {
        if (node == null){
            return;
        }
        inOrder(res, node.left);
        res.add(node.val);
        inOrder(res, node.right);
    }

    public static List<Integer> inOrderTraversal2(TreeNode root){
        List<Integer> res = new ArrayList<>();
        if (root == null){
            return res;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        TreeNode curr_node = root;
        while (curr_node != null || !deque.isEmpty()){
            if (curr_node != null){
                deque.push(curr_node);
                curr_node = curr_node.left;
            }
            else {
                curr_node = deque.pop();
                res.add(curr_node.val);
                curr_node = curr_node.right;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        TreeNode left = new TreeNode(2);
        TreeNode right = new TreeNode(3);
        TreeNode root = new TreeNode(1,left,right);

        List<Integer> integers_1 = inOrderTraversal(root);
        List<Integer> integers_2 = inOrderTraversal2(root);

        System.out.println(Arrays.toString(integers_1.toArray()));
        System.out.println(Arrays.toString(integers_2.toArray()));
    }

}
